#include "mutex.h"

#include <stdlib.h>

struct thread_mutex {
  int lock;
};

int thread_mutex_init(thread_mutex_t **mutex)
{
  *mutex = malloc(sizeof(thread_mutex_t));
  (*mutex)->lock = 0;

  return 0;
}

int thread_mutex_lock(thread_mutex_t *mutex)
{
  while (__sync_val_compare_and_swap(&(mutex->lock), 0, 1) == 1);

  return 0;
}

int thread_mutex_unlock(thread_mutex_t *mutex)
{
  __sync_and_and_fetch(&(mutex->lock), 0);

  return 0;
}

int thread_mutex_destroy(thread_mutex_t *mutex)
{
  free(mutex);

  return 0;
}
